//
//  ViewController.swift
//  iOS
//
//  Created by gongkai on 15/4/17.
//  Copyright (c) 2015年 gongkai. All rights reserved.
//

import UIKit
import Alamofire

let kUserName = "username"
let kPwd = "pwd"

class LoginViewController: BaseViewController {
    @IBOutlet weak var uNameView: UITextField!
    @IBOutlet weak var uPwdView: UITextField!
    @IBOutlet weak var autoLoginView: UISwitch!

    override func viewDidLoad() {
        super.viewDidLoad()
        
    }

    //MARK: 登录
    @IBAction func onLogin(sender: UIButton) {
        if(uNameView.text.length==0){
            Hinter.toast("用户名不能为空")
            uNameView.becomeFirstResponder()
            return;
        }
        
        if(uPwdView.text.length==0){
            Hinter.toast("密码不能为空")
            uPwdView.becomeFirstResponder()
            return;
        }
        
        Hinter.loadingToast("登录中...")
        var params = [kUserName:uNameView.text,kPwd:uPwdView.text]
        Alamofire.request(.POST, api_login, parameters: params).responseJSON { (_, _, JSON, _) in
            println(JSON)
            Hinter.hideToast()
            if let dict = JSON as? Dictionary<String,AnyObject>{
                let status = dict["state"] as! Int
                if let result = dict["result"] as? Dictionary<String,AnyObject> where status == 0{
                    
                    //保存用户信息
                    let df = NSUserDefaults.standardUserDefaults()
                    df.setValue(result["uid"], forKey: "uid")
                    df.synchronize()
                    
                    self.goMain()
                }else if(status == 1){
                    Hinter.loadingToast("用户名或密码有误")
                }
            }
            Hinter.netWorkTimeOutAlert()
        }
    }

    func goMain(){
        let mainCtr = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() as! UIViewController
        UIUtils.setRootViewController(mainCtr)
    }
    
}

